//HomePage.vue
<template>
  <div class="home">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-content">
        <div class="logo">
          <h1>在线商城</h1>
        </div>
        <el-menu mode="horizontal" :router="true" class="nav-menu">
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/user">个人中心</el-menu-item>
        </el-menu>
        <div class="user-actions">
          <el-input
            v-model="searchKey"
            placeholder="搜索商品"
            prefix-icon="Search"
            class="search-input"
            @input="searchProducts"
          />
          <!-- 收藏夹按钮 -->
          <el-button type="danger" icon="el-icon-star" @click="goToFavorites">收藏夹</el-button>
          <!-- 登录按钮 -->
          <el-button type="info" @click="goToLogin" v-if="!isLoggedIn">登录/注册</el-button>
          <el-button type="primary" :icon="cart" @click="goToCart">购物车</el-button>
        </div>
      </div>
    </el-header>

    <!-- 轮播图 -->
    <div class="banner">
      <el-carousel height="400px">
        <el-carousel-item v-for="(item, index) in bannerList" :key="index">
          <img :src="getBannerImageUrl(index)" :alt="item.title">
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 商品分类部分 -->
    <div class="category-filter">
      <el-card class="filter-card">
        <template #header>
          <div class="card-header">
            <span>商品分类</span>
          </div>
        </template>

        <!-- 分类列表 -->
        <div class="category-list">
          <el-menu
            mode="horizontal"
            :default-active="selectedCategory ? selectedCategory.toString() : ''"
            class="category-menu"
            @select="handleCategorySelect"
          >
            <!-- 显示"全部"选项 -->
            <el-menu-item index="0">全部</el-menu-item>

            <!-- 一级分类及其子分类 -->
            <template v-for="category in topLevelCategories" :key="category.categoryId">
              <el-sub-menu
                :index="category.categoryId.toString()"
                popper-class="category-submenu"
              >
                <template #title>{{ category.name }}</template>
                <!-- 子分类 -->
                <el-menu-item
                  v-for="subCategory in getChildCategories(category.categoryId)"
                  :key="subCategory.categoryId"
                  :index="subCategory.categoryId.toString()"
                >
                  {{ subCategory.name }}
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </div>
      </el-card>
    </div>

    <!-- 商品列表 -->
    <div class="hot-products">
      <h2>商品</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in hotProducts" :key="product.id">
          <el-card
            class="product-card"
            shadow="hover"
            @click="goToProductDetail(product)"
          >
            <el-image
              :src="product.image"
              class="product-image"
              fit="cover"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </template>
            </el-image>
            <div class="product-info">
              <h3>{{ product.title }}</h3>
              <p class="price">¥{{ ((product.price || 0) / 100).toFixed(2) }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-pagination
        v-model:current-page="currentPage3"
        v-model:page-size="pageSize3"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="prev, pager, next, jumper"
        :total="1000"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { Picture } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 数据声明
const searchKey = ref('')
const hotProducts = ref([])
const categories = ref([])
const bannerList = ref([])
const isLoggedIn = ref(false)
const currentPage3 = ref(1)
const pageSize3 = ref(20)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)
const selectedCategory = ref(null)
// const categoriesLoading = ref(false)

// 获取子分类的方法
const getChildCategories = (parentId) => {
  return categories.value
    .filter(category => category.parentId === parentId && category.status === 1)
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
}

// 计算顶级分类
const topLevelCategories = computed(() => {
  return categories.value
    .filter(category => category.parentId === 0)
    .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
})

// 获取子分类的方法
// const getChildCategories = (parentId) => {
//   return categories.value
//     .filter(category => category.parentId === parentId)
//     .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
// }

// 获取分类数据
const getCategories = async () => {
  try {
    const response = await axios.get('/categories/all')
    if (response.data && Array.isArray(response.data)) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 处理分类选择
const handleCategorySelect = (categoryId) => {
  categoryId = parseInt(categoryId)
  if (categoryId === 0) {
    selectedCategory.value = null
    getHotProducts() // 显示所有商品
  } else {
    selectedCategory.value = categoryId
    filterByCategory(categoryId)
  }
}

// 按分类筛选商品
const filterByCategory = async (categoryId) => {
  try {
    if (!categoryId) {
      await getHotProducts()
      return
    }

    const response = await axios.get('/logic/item/listByCategory', {
      params: {
        categoryId: categoryId,
        pageNum: currentPage3.value,
        pageSize: pageSize3.value
      }
    })
    hotProducts.value = response.data.filter(product => product.status === 1)
  } catch (error) {
    console.error('按分类筛选商品失败:', error)
  }
}

// 获取分类数据
// const getCategories = async () => {
//   try {
//     const response = await axios.get('/logic/category/list')
//     console.log('分类数据响应:', response.data) // 调试日志
//     if (response.data && Array.isArray(response.data)) {
//       categories.value = response.data.filter(category => category.status === 1)
//       console.log('处理后的分类数据:', categories.value) // 调试日志
//     } else {
//       console.error('分类数据格式不正确:', response.data)
//     }
//   } catch (error) {
//     console.error('获取分类失败:', error)
//   }
// }
//
// // 处理分类选择
// const handleCategorySelect = (categoryId) => {
//   selectedCategory.value = parseInt(categoryId)
//   filterByCategory(selectedCategory.value)
// }
//
// // 按分类筛选商品
// const filterByCategory = async (categoryId) => {
//   try {
//     if (!categoryId) {
//       await getHotProducts()
//       return
//     }
//
//     const response = await axios.get('/logic/item/listByCategory', {
//       params: {
//         categoryId: categoryId,
//         pageNum: currentPage3.value,
//         pageSize: pageSize3.value
//       }
//     })
//     hotProducts.value = response.data.filter(product => product.status === 1)
//   } catch (error) {
//     console.error('按分类筛选商品失败:', error)
//   }
// }

// 页大小改变时的回调
const handleSizeChange = (val) => {
  pageSize3.value = val
  getHotProducts()
}

// 当前页改变时的回调
const handleCurrentChange = (val) => {
  currentPage3.value = val
  getHotProducts()
}

// 获取轮播图图片URL
const getBannerImageUrl = (index) => {
  // 实现获取轮播图URL的逻辑
  return `path/to/banner/${index}.jpg`
}

// 获取商品列表
const getHotProducts = async () => {
  try {
    const response = await axios.get('/logic/item/list', {
      params: {
        pageNum: currentPage3.value,
        pageSize: pageSize3.value
      }
    })
    hotProducts.value = response.data.filter(product => product.status === 1)
  } catch (error) {
    console.error('获取商品失败:', error)
  }
}

// 搜索商品
const searchProducts = async () => {
  if (!searchKey.value) {
    getHotProducts()
    return
  }

  try {
    const response = await axios.get('/logic/item/listByCategory', {
      params: {
        title: searchKey.value
      }
    })
    hotProducts.value = response.data
  } catch (error) {
    console.error('搜索商品失败:', error)
  }
}

// 跳转到商品详情页
const goToProductDetail = (product) => {
  router.push({
    path: `/product/${product.id}`,
    query: {
      productDetail: JSON.stringify(product)
    }
  })
}

// 跳转到收藏夹页
const goToFavorites = () => {
  router.push('/Favorites')
}

// 跳转到购物车页
const goToCart = () => {
  router.push('/cart')
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 页面加载时执行
onMounted(async () => {
  try {
    console.log('页面加载，开始获取数据') // 调试日志
    await getCategories() // 先获取分类
    await getHotProducts() // 再获取商品
    console.log('数据加载完成') // 调试日志
  } catch (error) {
    console.error('数据加载失败:', error)
  }
})
</script>

<style scoped>
/* 全局样式 */
.home {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  height: 70px !important;
  padding: 0;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
}

.logo h1 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(45deg, #409EFF, #36D1DC);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

/* 导航菜单样式 */
.nav-menu {
  border-bottom: none;
  background: transparent;
  margin-left: 40px;
}

.nav-menu :deep(.el-menu-item) {
  font-size: 16px;
  color: #606266;
  height: 70px;
  line-height: 70px;
}

.nav-menu :deep(.el-menu-item.is-active) {
  color: #409EFF;
  border-bottom: 3px solid #409EFF;
}

/* 用户操作区域样式 */
.user-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 20px;
  height: 40px;
}

/* 轮播图样式 */
.banner {
  margin: 90px auto 30px;
  max-width: 1400px;
  border-radius: 12px;
  overflow: hidden;
}

.banner :deep(.el-carousel__item) {
  border-radius: 12px;
}

.banner img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
}

/* 分类过滤器样式 */
.category-filter {
  max-width: 1400px;
  margin: 30px auto;
}

.filter-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.category-menu {
  border-right: none;
  width: 100%;
}

.filter-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
  border-radius: 12px 12px 0 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.category-list {
  padding: 10px;
}

/* 分类菜单样式 */
.category-menu :deep(.el-menu-item) {
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
}

.category-menu :deep(.el-sub-menu__title) {
  height: 40px;
  line-height: 40px;
}

.category-menu :deep(.el-menu-item.is-active) {
  background-color: #ecf5ff;
  color: #409EFF;
}

/* 商品卡片样式 */
.hot-products {
  max-width: 1400px;
  margin: 40px auto;
  padding: 0 20px;
}

.hot-products h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
  font-weight: bold;
  position: relative;
  padding-left: 15px;
}

.hot-products h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(45deg, #409EFF, #36D1DC);
  border-radius: 2px;
}

.product-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 25px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.product-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 220px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  padding: 15px;
}

.product-info h3 {
  margin: 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  color: #ff6b6b;
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
  display: flex;
  align-items: center;
}

.price::before {
  content: '¥';
  font-size: 14px;
  margin-right: 2px;
}

/* 分页器样式 */
.el-pagination {
  margin-top: 40px;
  text-align: center;
  padding: 20px 0;
}

/* 按钮样式优化 */
.user-actions :deep(.el-button) {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.user-actions :deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式布局优化 */
@media screen and (max-width: 1200px) {
  .header-content,
  .banner,
  .hot-products {
    max-width: 960px;
  }

  .search-input {
    width: 250px;
  }
}

@media screen and (max-width: 768px) {
  .header-content {
    padding: 0 15px;
  }

  .logo h1 {
    font-size: 20px;
  }

  .search-input {
    width: 200px;
  }

  .user-actions {
    gap: 10px;
  }

  .product-card {
    margin-bottom: 15px;
  }
}

/* 图片占位符样式 */
.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-placeholder .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

/* 分类菜单扩展样式 */
.category-menu {
  border-right: none !important;
}

.category-menu :deep(.el-sub-menu) {
  width: 100%;
}

.category-menu :deep(.el-menu-item),
.category-menu :deep(.el-sub-menu__title) {
  height: 45px !important;
  line-height: 45px !important;
  font-size: 14px;
}

.category-menu :deep(.el-sub-menu .el-menu-item) {
  min-width: auto;
  padding-left: 48px !important;
  background-color: #f9f9f9;
}

.category-menu :deep(.el-menu--inline) {
  background-color: #f9f9f9;
}

.category-menu :deep(.el-menu-item.is-active) {
  background-color: #ecf5ff;
  color: #409EFF;
}

.category-count {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.loading-state {
  padding: 20px;
}

/* 优化分类卡片样式 */
.filter-card {
  margin-bottom: 20px;
}

.filter-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .el-button {
  padding: 0;
  font-size: 14px;
}
</style>
